import JsonSeriable from "../base/JsonSeriable"
import JsonSeriType from "../base/JsonSeriType"
import commonConstants from "../constants/commonConstants"

export default class FieldHandler extends JsonSeriable{
	
	#fieldGroups = [];
	#fieldMap = {};
	
	constructor(){
		super();
		super.seriType = new JsonSeriType(commonConstants.fieldHandler.FieldHandler.code,commonConstants.fieldHandler.FieldHandler.clsPage);
	}
	init(initObj){
		if(!initObj){
			return;
		}
		this.#fieldGroups = [];
		this.#fieldMap = {};
		if(initObj.fieldGroups){
			this.#fieldGroups = initObj.fieldGroups;
			for(let fix  = 0; fix< initObj.fieldGroups.length; fix ++){
				let fields = initObj.fieldGroups[fix].getFields();
				for(let field of fields){
					if(!field){
						continue;
					}
					if(this.#fieldMap[field.code]){
						this.#fieldMap[field.code].push(field);
					}else{
						this.#fieldMap[field.code] = [].concat(field);
					}
				}
			}
		}
	}
	
	getFieldValue(fcode){
		if(this.#fieldMap[fcode]){
			return this.#fieldMap[fcode][0].value;
		}
		return null;
	}
	
	getField(fcode){
		let fs = this.#fieldMap[fcode];
		if(fs && fs.length > 0){
			return fs[0];
		}
		return null;
	}
	
	setFieldValue(fcode,value){
		let gf = this.getField(fcode);
		if(gf){
			gf.value = value;
		}
	}
	
	getAllFields(){
		let ret = [];
		for(let fix  = 0; fix< this.#fieldGroups.length; fix ++){
			ret = [...ret,...this.#fieldGroups[fix].fieldList];
		}
		return ret;
	}
	
	getAll(){
		return this.#fieldGroups;
	}
}